<?php
namespace Common\Model;

//微信接口
class ApiModel{
    
    public static $errCode = array(
        '-1' => '系统繁忙',
        '0' => '请求成功',
        '40001' => '获取access_token时AppSecret错误，或者access_token无效',
        '40002' => '不合法的凭证类型',
        '40003' => '不合法的OpenID',
        '40004' => '不合法的媒体文件类型',
        '40005' => '不合法的文件类型',
        '40006' => '不合法的文件大小',
        '40007' => '不合法的媒体文件id',
        '40008' => '不合法的消息类型',
        '40009' => '不合法的图片文件大小',
        '40010' => '不合法的语音文件大小',
        '40011' => '不合法的视频文件大小',
        '40012' => '不合法的缩略图文件大小',
        '40013' => '不合法的APPID',
        '40014' => '不合法的access_token',
        '40015' => '不合法的菜单类型',
        '40016' => '不合法的按钮个数',
        '40017' => '不合法的按钮类型',
        '40018' => '不合法的按钮名字长度',
        '40019' => '不合法的按钮KEY长度',
        '40020' => '不合法的按钮URL长度',
        '40021' => '不合法的菜单版本号',
        '40022' => '不合法的子菜单级数',
        '40023' => '不合法的子菜单按钮个数',
        '40024' => '不合法的子菜单按钮类型',
        '40025' => '不合法的子菜单按钮名字长度',
        '40026' => '不合法的子菜单按钮KEY长度',
        '40027' => '不合法的子菜单按钮URL长度',
        '40028' => '不合法的自定义菜单使用用户',
        '40029' => '不合法的oauth_code',
        '40030' => '不合法的refresh_token',
        '40031' => '不合法的openid列表',
        '40032' => '不合法的openid列表长度',
        '40033' => '不合法的请求字符，不能包含\uxxxx格式的字符',
        '40035' => '不合法的参数',
        '40038' => '不合法的请求格式',
        '40039' => '不合法的URL长度',
        '40050' => '不合法的分组id',
        '40051' => '分组名字不合法',
        '40099' => '该 code 已被核销',
        '41001' => '缺少access_token参数',
        '41002' => '缺少appid参数',
        '41003' => '缺少refresh_token参数',
        '41004' => '缺少secret参数',
        '41005' => '缺少多媒体文件数据',
        '41006' => '缺少media_id参数',
        '41007' => '缺少子菜单数据',
        '41008' => '缺少oauth code',
        '41009' => '缺少openid',
        '42001' => 'access_token超时',
        '42002' => 'refresh_token超时',
        '42003' => 'oauth_code超时',
        '42005' => '调用接口频率超过上限',
        '43001' => '需要GET请求',
        '43002' => '需要POST请求',
        '43003' => '需要HTTPS请求',
        '43004' => '需要接收者关注',
        '43005' => '需要好友关系',
        '44001' => '多媒体文件为空',
        '44002' => 'POST的数据包为空',
        '44003' => '图文消息内容为空',
        '44004' => '文本消息内容为空',
        '45001' => '多媒体文件大小超过限制',
        '45002' => '消息内容超过限制',
        '45003' => '标题字段超过限制',
        '45004' => '描述字段超过限制',
        '45005' => '链接字段超过限制',
        '45006' => '图片链接字段超过限制',
        '45007' => '语音播放时间超过限制',
        '45008' => '图文消息超过限制',
        '45009' => '接口调用超过限制',
        '45010' => '创建菜单个数超过限制',
        '45015' => '回复时间超过限制',
        '45016' => '系统分组，不允许修改',
        '45017' => '分组名字过长',
        '45018' => '分组数量超过上限',
        '45024' => '账号数量超过上限',
        '46001' => '不存在媒体数据',
        '46002' => '不存在的菜单版本',
        '46003' => '不存在的菜单数据',
        '46004' => '不存在的用户',
        '47001' => '解析JSON/XML内容错误',
        '48001' => 'api功能未授权',
        '50001' => '用户未授权该api',
        '61450' => '系统错误',
        '61451' => '参数错误',
        '61452' => '无效客服账号',
        '61453' => '账号已存在',
        '61454' => '客服帐号名长度超过限制(仅允许10个英文字符，不包括@及@后的公众号的微信号)',
        '61455' => '客服账号名包含非法字符(英文+数字)',
        '61456' => '客服账号个数超过限制(10个客服账号)',
        '61457' => '无效头像文件类型',
        '61458' => '客户正在被其他客服接待',
        '61459' => '客服不在线',
        '61500' => '日期格式错误',
        '61501' => '日期范围错误',
        '7000000' => '请求正常，无语义结果',
        '7000001' => '缺失请求参数',
        '7000002' => 'signature 参数无效',
        '7000003' => '地理位置相关配置 1 无效',
        '7000004' => '地理位置相关配置 2 无效',
        '7000005' => '请求地理位置信息失败',
        '7000006' => '地理位置结果解析失败',
        '7000007' => '内部初始化失败',
        '7000008' => '非法 appid（获取密钥失败）',
        '7000009' => '请求语义服务失败',
        '7000010' => '非法 post 请求',
        '7000011' => 'post 请求 json 字段无效',
        '7000030' => '查询 query 太短',
        '7000031' => '查询 query 太长',
        '7000032' => '城市、经纬度信息缺失',
        '7000033' => 'query 请求语义处理失败',
        '7000034' => '获取天气信息失败',
        '7000035' => '获取股票信息失败',
        '7000036' => 'utf8 编码转换失败',
    );
    /**
     * 网页授权获取用户信息-获取code
     * @param $redirectUri string 回调链接地址
     */
    public function getAuthCode($redirectUri, $appid){
        $redirectUri = urlencode($redirectUri);
        header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirectUri."&response_type=code&scope=snsapi_base&state=123#wechat_redirect");die;
    }
    
    /**
     * 网页授权获取用户信息-code换取网页授权access_token
     * @param $code string
     * @return 用户openid
     */
    public function getAuthOpenid($wx_code, $appid, $secret){
        if(empty($wx_code)) return false;
        $wx_user_json = $this->curl_request("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$wx_code."&grant_type=authorization_code");
        $wx_res = json_decode($wx_user_json,true);
        return $wx_res['openid'];
    }
    
    /**
     * 获取用户基本信息
     */
    public function getUserInfo($access_token, $openid){
        if(empty($access_token) || empty($openid)) return false;
        $wx_user_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN");
        $wx_res = json_decode($wx_user_json,true);
        return $wx_res;
    }
    
    /**
     * 获取是公众号的全局唯一票据access_token
     * @param $appid string
     * @param $secret string
     */
    public function getAccessToken($appid = '', $secret = ''){
        if(empty($appid) || empty($secret)) return false;
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret);
        $wx_res = json_decode($wx_json,true);
        return $wx_res;
    }
    
    /**
     * 创建自定义菜单
     */
    public function createMenu($access_token = '', $data = array()){
        if(empty($access_token) || empty($data)) return false;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token,$data);
        $wx_res = json_decode($wx_json,true);
        if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    /**
     * 创建分组
     * {"group":{"name":"test"}}
     */
    public function createGroup($access_token = '', $data = array()){
    	if(empty($access_token) || empty($data)) return false;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$access_token,$data);
        $wx_res = json_decode($wx_json,true);
        if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    
    /**
     * 修改分组名
     * {"group":{"id":108,"name":"test2_modify2"}}
     */
    public function modifyGroup($access_token = '', $data = array()){
    	if(empty($access_token) || empty($data)) return false;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/groups/update?access_token=".$access_token,$data);
        $wx_res = json_decode($wx_json,true);
        if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    
    /**
     * 查询所有分组
     */
    public function getGroups($access_token = ''){
    	if(empty($access_token)) return false;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/groups/get?access_token=".$access_token,$data);
        $wx_res = json_decode($wx_json,true);
        if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    
    /**
     * 移动分组
     * {"openid":"oDF3iYx0ro3_7jD4HFRDfrjdCM58","to_groupid":108}
     */
    public function moveGroup($access_token = '', $data = array()){
    	if(empty($access_token) || empty($data)) return false;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$access_token,$data);
        $wx_res = json_decode($wx_json,true);
        if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    
    /**
     * 批量移动分组
     * {"openid_list":["oDF3iYx0ro3_7jD4HFRDfrjdCM58","oDF3iY9FGSSRHom3B-0w5j4jlEyY"],"to_groupid":108}
     */
    public function moveGroups($access_token = '', $data = array()){
    	if(empty($access_token) || empty($data)) return false;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=".$access_token,$data);
        $wx_res = json_decode($wx_json,true);
        if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    /**
     * 删除分组
     * {"group":{"id":108}}
     */
    public function deleteGroup($access_token = '', $data = array()){
    	if(empty($access_token) || empty($data)) return false;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $wx_json = $this->curl_request("https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=".$access_token,$data);
        $wx_res = json_decode($wx_json,true);
        if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    /**
     * 上传临时图片素材
     */
    public function upTempImage($access_token = '', $pic=''){
    	if(empty($access_token) || empty($pic)) return false;
    	$upFileUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=image";
    	$data = array('media'=>'@'.$pic);
    	$wx_json = $this->curl_request($upFileUrl, $data);
    	$wx_res = json_decode($wx_json,true);
    	if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    /**
     * 发送微信消息
     * @param string $access_token
     * @param string $content
     */
    public function sendWxMsg($access_token = '', $openid='', $content=''){
    	if(empty($access_token) || empty($content)) return false;
    	$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
    	$data = "{
                \"touser\":\"$openid\",
                \"msgtype\":\"text\",
                \"text\":
                {
                     \"content\":\"$content\"
                }
            }";
    	$wx_json = $this->curl_request($url, $data);
    	$wx_res = json_decode($wx_json,true);
    	if(!empty($wx_res['errcode'])){
    		return $this->getErrText($wx_res['errcode']);
    	}else{
    		return $wx_res;
    	}
    }
    /**
     * 上传永久图片素材
     */
    public function upImage($access_token = '', $pic=''){
    	if(empty($access_token) || empty($pic)) return false;
    	$upFileUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$access_token}&type=image";
    	$data = array('media'=>'@'.$pic);
    	$wx_json = $this->curl_request($upFileUrl, $data);
    	$wx_res = json_decode($wx_json,true);
    	if(!empty($wx_res['errcode'])){
            return $this->getErrText($wx_res['errcode']);
        }else{
            return $wx_res;
        }
    }
    /**
     * 获取粉丝openID列表
     * @param string $access_token
     * @param string $next_openid
     * @return boolean|unknown
     */
    public function getUsers($access_token = '',$next_openid = ''){
    	if(empty($access_token)) return false;
    	$upFileUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&next_openid=$next_openid";
    	$wx_json = $this->curl_request($upFileUrl);
    	$wx_res = json_decode($wx_json,true);
    	if(!empty($wx_res['errcode'])){
    		return $this->getErrText($wx_res['errcode']);
    	}else{
    		return $wx_res;
    	}
    }
    public function curl_request($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function getErrText($err) {
        if (isset(self::$errCode[$err])) {
            return self::$errCode[$err];
        } else {
            return false;
        };
    }
    
}